package models

import (
	"errors"
	"rongyy/src/app"
	"rongyy/src/middlewares"
)

type DiseaseModel struct {
	BaseModel  `xorm:"extends"`
	Name       string `json:"name"`
	NamePinyin string `json:"name_pinyin"`
	NameHead   string `json:"name_head"`
}

func (sm *DiseaseModel) TableName() string {
	return "disease"
}

func (sm *DiseaseModel) Insert() error {
	_, err := app.DB().Insert(sm)
	if err != nil {
		return err
	}
	return nil
}

func (sm *DiseaseModel) SelectByName(name string) (*DiseaseModel, error) {
	doc := &DiseaseModel{}
	has, err := app.DB().Where("name = ?", name).Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by DiseaseModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *DiseaseModel) SelectById(id string) (*DiseaseModel, error) {
	doc := &DiseaseModel{}
	has, err := app.DB().Where("id = ?", id).Get(doc)
	if err != nil {
		middlewares.Logger.Println("find by DiseaseModel", err)
		return nil, err
	}
	if !has {
		return nil, nil
	}
	return doc, err
}

func (sm *DiseaseModel) UpdateData(req *DiseaseModel, id string) error {
	_, err := app.DB().Where("id = ?", id).Cols("name", "name_pinyin", "name_head",
		"updated_by", "updated_at").Update(req)
	if err != nil {
		middlewares.Logger.Println("DiseaseModel Update failed ", err)
		return errors.New("数据修改失败")
	}
	return nil
}

func (sm *DiseaseModel) SelectAll() ([]DiseaseModel, error) {
	doc := make([]DiseaseModel, 0)
	s := app.DB().Table("disease").OrderBy("name_pinyin asc").Where("deleted_at is null")

	_, err := s.FindAndCount(&doc)
	if err != nil {
		return nil, err
	}
	return doc, err
}

func (sm *DiseaseModel) DeleteDisease(id string) error {
	doc := &DiseaseModel{}
	_, err := app.DB().Where("id = ?", id).Delete(doc)
	if err != nil {
		middlewares.Logger.Println("delete by DeleteDisease", err)
		return err
	}
	return err
}
